"""快速截图CG,目标是监视一个按键,一旦按下就截图指定区域并快速保存到文件"""

import os

from pynput import keyboard
from PIL import ImageGrab


class FastCGCapturer:
  """主类,需手动设定截图按键等参数.
  设置监控按键和截图行为,新建实例后直接用main()执行"""

  ### 设定项目
  ## 设定按键
  KEY_CAPTURE = keyboard.KeyCode.from_char('a') # 截图按键
  KEY_ESC = keyboard.Key.esc # 退出按键
  ## 设定保存路径和保存格式
  SAVE_PATH = os.path.dirname(__file__)+r'\艳女医'
  SAVE_FORMAT = 'JPEG'
  ## 设定保存的矩形区域
  LEFT, TOP, RIGHT, BOTTOM = 280, 68, 1079, 669
  BOX = (LEFT, TOP, RIGHT, BOTTOM)
  ## 设置保存图片的名字前缀和id初值,id初值建议用10000,方便增加后文件名长度对齐
  NAME_START = 'mizuki'
  ID_START = 10000

  def __init__(self):
    """初始化id数字"""
    self._id = self.ID_START
    return

  def _on_press(self, key):
    """捕捉按键行为设定"""
    if key == self.KEY_ESC: # esc键退出,返回False即退出
      print('Script finished!')
      return False
    if key == self.KEY_CAPTURE: # 保存截图到文件,并增加ID
      im = ImageGrab.grab(bbox = self.BOX)
      picFile = f'{self.NAME_START}{str(self._id)}.'+self.SAVE_FORMAT
      picFilePath = os.path.join(self.SAVE_PATH, picFile)
      im.save(picFilePath, SAVE_FORMAT)
      print(f'{picFile} saved')
      self._id += 1
    return True

  def main(self):
    """主函数,设置按键监听"""
    with keyboard.Listener(on_press = self._on_press) as listener:
      listener.join()
    return
    
    
if __name__ == '__main__':
  FastCGCapturer().main()